package edu.whu.webgis.security;

import edu.whu.webgis.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 创建一个UserDetailsService的Bean，从数据库中读取用户和权限信息
 */
@Service
public class DbUserDetailService implements UserDetailsService {

    @Autowired
    UserServiceImpl userServiceImpl;

    @Override
    public UserDetails loadUserByUsername(String userid) throws UsernameNotFoundException {

        edu.whu.webgis.entity.User user = userServiceImpl.getUser(userid);


        if (user == null) {
            throw new UsernameNotFoundException("User " + userid + " is not found");
        }
//        List<GrantedAuthority> authorities = new ArrayList<>();
//        for (Role role : user.getRoles()) {
//            for (String auth : role.getAuthorities()) {
//                authorities.add(new SimpleGrantedAuthority(auth));
//            }
//        }
        return User.builder()
                .username(userid)
                //注：正式项目最好在数据库用密文存储密码
                .password(new BCryptPasswordEncoder().encode(user.getPasswd()))
                .roles("admin")
                //.authorities(authorities.toArray(new GrantedAuthority[authorities.size()]))
                .build();
    }


}
